#!/usr/bin/env python3
"""
随手记 CLI
用法:
  python note.py add  "买牛奶"
  python note.py list
  python note.py find 牛奶
  python note.py del 3
数据保存在 notes.json
"""
import json, sys, datetime, os

DB = "notes.json"

def load_notes():
    if not os.path.exists(DB):
        return []
    with open(DB, "r", encoding="utf-8") as f:
        return json.load(f)

def save_notes(notes):
    with open(DB, "w", encoding="utf-8") as f:
        json.dump(notes, f, ensure_ascii=False, indent=2)

def add_note(text):
    notes = load_notes()
    notes.append({
        "id": len(notes) + 1,
        "text": text,
        "time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    })
    save_notes(notes)
    print("已添加：", text)

def list_notes():
    notes = load_notes()
    if not notes:
        print("暂无记录")
        return
    for n in notes:
        print(f"{n['id']:>3} | {n['time']} | {n['text']}")

def find_notes(key):
    notes = load_notes()
    found = [n for n in notes if key in n["text"]]
    if not found:
        print("未找到匹配记录")
        return
    for n in found:
        print(f"{n['id']:>3} | {n['time']} | {n['text']}")

def del_note(nid):
    notes = load_notes()
    new_notes = [n for n in notes if n["id"] != nid]
    if len(new_notes) == len(notes):
        print("ID 不存在")
        return
    # 重排 ID
    for idx, n in enumerate(new_notes, 1):
        n["id"] = idx
    save_notes(new_notes)
    print("已删除 ID:", nid)

def usage():
    print("用法:")
    print("  python note.py add  <内容>   # 新增")
    print("  python note.py list          # 列出全部")
    print("  python note.py find <关键词> # 查找")
    print("  python note.py del  <ID>     # 删除")
    sys.exit(1)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        usage()
    cmd = sys.argv[1].lower()
    if cmd == "add" and len(sys.argv) >= 3:
        add_note(" ".join(sys.argv[2:]))
    elif cmd == "list":
        list_notes()
    elif cmd == "find" and len(sys.argv) >= 3:
        find_notes(sys.argv[2])
    elif cmd == "del" and len(sys.argv) >= 3:
        try:
            del_note(int(sys.argv[2]))
        except ValueError:
            print("ID 必须是数字")
    else:
        usage()